package mongo

import (
	"autoTestNew/pkg/config"
	"autoTestNew/pkg/mongo/autoTestNew/apiDoc"
	"autoTestNew/pkg/mongo/autoTestNew/record"
	"autoTestNew/pkg/mongo/autoTestNew/task"
	"autoTestNew/pkg/mongo/autoTestNew/testCase"
	"autoTestNew/pkg/mongo/autoTestNew/testMicroservice"
	"context"
	"github.com/go-logr/logr"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/fx"
)

var (
	// Module includes the providers provided by store.
	Module = fx.Options(
		fx.Provide(
			apiDoc.NewStore,
			record.NewStore,
			testCase.NewStore,
			testMicroservice.NewStore,
			task.NewStore,
		),
	)
)

// NewMongoDBStore returns a new mongo.Database
func NewMongoDBStore(lc fx.Lifecycle, conf *config.MongoDBConfig, logger logr.Logger) (*mongo.Database, error) {
	logger.Info("Connecting to MongoDB", "URI", conf.URI, "database", conf.Database)

	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(conf.URI))
	if err != nil {
		logger.Error(err, "Failed to connect mongodb", "URI", conf.URI)
		return nil, err
	}

	lc.Append(fx.Hook{
		OnStop: func(ctx context.Context) error {
			return client.Disconnect(ctx)
		},
	})

	// 立即检查连接
	err = client.Ping(context.Background(), nil)
	if err != nil {
		logger.Error(err, "Failed to ping mongodb", "URI", conf.URI)
		return nil, err
	}

	mongoDatabase := client.Database(conf.Database)

	return mongoDatabase, nil
}
